package com.ruoyi.web.controller.scanCodeLogin;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.CodeLogin;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@RequestMapping("/scan-code-login")
public class AdminAppScanCodeLoginController extends BaseController {
    @Resource
    private RedisCache redisCache;

    @GetMapping("/confirm")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult confirmLogin(@RequestParam String token) {
        //当前登录人Id
        Long currentUserId = getUserId();
        //判断token存在，userId正确
        String status = redisCache.getCacheObject(CacheConstants.SCAN_CODE_LOGIN_KEY + token);
        if (!Objects.isNull(status)) {
            if (Objects.equals(CodeLogin.NOT_SCANNED.getCode(), status)) {
                //删除
                redisCache.deleteObject(CacheConstants.SCAN_CODE_LOGIN_KEY + token);
                //设置新的redis进行登录携带userId
                redisCache.setCacheObject(CacheConstants.SCAN_CODE_LOGIN_KEY + token, CodeLogin.SUCCESS.getCode() + "-" + currentUserId, 5, TimeUnit.SECONDS);
            }
        }
        return success();
    }

}
